package com.wrb.pwd.config;

import com.alibaba.fastjson.JSON;
import com.wrb.pwd.constant.Constant;
import com.wrb.pwd.service.UserService;
import com.wrb.pwd.utils.SecurityAES;
import sun.misc.IOUtils;

import java.io.*;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.JarOutputStream;

/**
 * @author wrb
 * @date 2019/9/12 14:45
 */
public class RePackageThread extends Thread {

	@Override
	public void run() {
		pack();
	}

	/**
	 * 打包jar包并把内存资源导入
	 */
	private void pack() {
		try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
			String jarPath = RePackageThread.class.getProtectionDomain().getCodeSource().getLocation().getPath();
			jarPath = URLDecoder.decode(jarPath, "utf-8");
			try (
					JarFile jarFile = new JarFile(jarPath);
					JarOutputStream jos = new JarOutputStream(byteArrayOutputStream)
			) {
				jarFile.stream().forEach(entry -> {
//					System.out.println(entry.getName());
					try (InputStream is = jarFile.getInputStream(entry)) {
						jos.putNextEntry(new JarEntry(entry.getName()));

						if (Constant.DATA_FILE_NAME.equals(entry.getName())) {
							String s = JSON.toJSONString(UserService.getUserList());
							// AES加密
							String encrypt = SecurityAES.encrypt(s);
							assert encrypt != null;
							jos.write(encrypt.getBytes(StandardCharsets.UTF_8));
						} else if (Constant.PASSWORD_FILE_NAME.equals(entry.getName())) {
							String s = JSON.toJSONString(Constant.password);
							jos.write(s.getBytes(StandardCharsets.UTF_8));
						} else {
							jos.write(IOUtils.readNBytes(is, is.available()));
						}
						jos.closeEntry();
					} catch (Exception e) {
						e.printStackTrace();
					}
				});
			}

			byteArrayOutputStream.writeTo(new FileOutputStream(jarPath));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
